<?php
namespace app\common\logic\ad\driver;


use app\common\logic\ad\Driver;
use app\common\model\ad\Ads;
use app\common\utils\Utils;
use think\Db;
use think\Exception;
use think\exception\ValidateException;

/**
 * Created by PhpStorm.
 * User: yangchunfu
 * Date: 2019/12/24
 * Time: 4:36 PM
 */

class First extends Driver
{
    protected $options = [
    ];
    //1_5代表第一到第五广告  other 代表其他广告
    protected $rule = ['1_5', 'other'];

    protected $htmlTpl = 'first.html';
    protected $ruleWhere = [
        'mark' => 'first'
    ];

    protected $items = [
        '1' => '广告位1',
        '2' => '广告位2',
        '3' => '广告位3',
        '4' => '广告位4',
        '5' => '广告位5'
    ];
    //对规则做一下解析
    public function __construct($options)
    {
        parent::__construct($options);
        if (!$this->options['rule']) {
            throw new ValidateException('rule必须传递');
        }

    }






    /**
     * 获取规则html
     * @param int $ads_id
     * @return string
     * cast_item_id 0 代表小 1代表大
     */
    public function insertRule($ads_id = null)
    {

        //其他广告直接返回
        if (self::$curRule == 'other') {
            $cast_item_id = null;
            $all_little = $this->ruleModel->where($this->getRule())->where(['cast_item_id'=> 0])->count();
            $all_big = $this->ruleModel->where($this->getRule())->where(['cast_item_id'=> 1])->count();
            if ($ads_id) {
                $cast_item_id = $this->ruleModel->where($this->getRule())->where(['ad_ads_id' => $ads_id])->value('cast_item_id');
            } else {
                $type = $this->ruleModel->where($this->getRule())->where(['ad_ads_id' => $ads_id])->order('id desc')->value('cast_item_id');
                if (!$type) {
                    $cast_item_id = 0;
                } else {
                    $cast_item_id = $type == 0 ? 1 : 0;
                }

                //小的减去大的 添加的时候 需要注意的地方

                if (($all_little - $all_big >= 1) ) {
                    $cast_item_id = 1;
                } else if ($all_little - $all_big >= 1) {
                    $cast_item_id = 0;
                }
            }

            $tips = '小图总数:' . $all_little .',大图总数:'.$all_big . ';' . '小图，比例为（宽:高 = 214 : 166）;大图，比例为（宽:高 = 448 : 166）' ;
            $select_string = build_select('rules[cast_item_id]', ['0' => 'A组', '1' => 'B组'], $cast_item_id,[
                'class'=>'form-control',
                'data-rule'=>'required'
            ]);
            $html = <<<EOD
    <div style="color: red;background: wheat;padding: 10px;margin-bottom: 20px;">
        $tips
    </div>        
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">图片描述:</label>
        <div class="col-xs-12 col-sm-8">
            {$select_string}               
        </div>
    </div>
EOD;

            return $html;

        } else {

            $html = <<<EOD
        <div style="color: red;background: wheat;padding: 10px;margin-bottom: 20px;">
            广告位1:宽:高=436:256; 广告位2:宽:高=184:256; 广告位3:宽:高=184:166; 广告位4:宽:高=184:166; 广告位5:宽:高=436:356
        </div> 
    
EOD;

            return $html;

        }




        return '';
        $cast_item_id = null;
        if ($ads_id) {
            //$cast_item_id 代表的是广告位置1到5
            $cast_item_id = $this->ruleModel->where($this->getRule())->where(['ad_ads_id' => $ads_id])->value('cast_item_id');
        }

        $items = $this->items;
        $items = array_merge(['0' => '--请选择首页广告位置--'], $items);
        $select_string = build_select('rules[cast_item_id]', $items, $cast_item_id,[
            'class'=>'form-control',
            'data-rule'=>'required'
        ]);
        $html = <<<EOD
        
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">请选择广告位置:</label>
        <div class="col-xs-12 col-sm-8">
            {$select_string}               
        </div>
    </div>
EOD;

        return $html;
    }

    /**
     * 修改广告
     * @param array $data 要添加的数据
     * @param object $row 模型
     * @return mixed
     */
    public function edit(Ads $row, $data = []) {
        $rule_where = $this->getRule();
        $rule_where['ad_ads_id'] = $row->id;
        Db::startTrans();
        try {
            if (isset($this->options['cast_item_id'])) {
                $this->ruleModel->where($rule_where)->setField('cast_item_id', $this->options['cast_item_id']);
            }
            $row->allowField(true)->save($data);
            Db::commit();
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }


    /**
    /**
     * 获取规则
     * @return array
     */
    public function getRule() {
        $rule1 = self::$curRule;

        $rule = array_merge($this->ruleWhere, ['rule'=> $rule1]);

        return $rule;
    }

    /**
     * 检测规则
     * @return boolean
     */
    public function checkRule() {
        if (!in_array(self::$curRule, $this->rule)) {
            throw new ValidateException('规则条件传递不对');
        }

        return true;
    }



    /**********************************接口部分*/

    /**
     * 获取广告 接口 api
     * @return mixed
     */
    public function select($where = []){
        if (self::$curRule == '1_5') {
            //1 到 5广告 由小到大
            $ids = $this->ruleModel->where($this->getRule())->order('cast_item_id asc')->column('ad_ads_id');
            //获取一到5广告
            $ad = [];
            foreach ($ids as $k => $v) {
                $temp = $this->adModel->where('id', $v)->find();
                $ad[$k] = $temp ? $temp : null;
            }

            return $ad;
        } else {
            //获取广告数据
            $ad_little = $this->adModel->where('id','IN',function($query) {
                $query->name('self_ad_rule')->where($this->getRule())->where('cast_item_id', 0)->field('ad_ads_id');
            })->where($where)->order('weigh desc, createtime desc')->paginate(20)->each(function ($item, $key) {

            });

            $ad_big = $this->adModel->where('id','IN',function($query) {
                $query->name('self_ad_rule')->where($this->getRule())->where('cast_item_id', 1)->field('ad_ads_id');
            })->where($where)->order('weigh desc, createtime desc')->paginate(20)->each(function ($item, $key) {

            });

            $ads = [];  //排列循序 大小 小大 大小 小大  所有奇数是大小 所有偶数是小大
            if (count($ad_big) >= count($ad_little)) {
                foreach ($ad_big as $k => $v) {
                    if ($k%2 == 0){
                        array_push($ads, $v);  //大的在前
                        if (isset($ad_little[$k])) {
                            array_push($ads, $ad_little[$k]); //取得相同的键位
                        }
                    } else {
                        //小的在前
                        if (isset($ad_little[$k])) {
                            array_push($ads, $ad_little[$k]); //取得相同的键位
                        }
                        array_push($ads, $v);  //大的在前
                    }

                    //如果big没有对应的那么就把小的一直田间
                }
            } else {
                //大的大于小的 大在前
                foreach ($ad_little as $k => $v) {
                    if ($k%2 == 0){
                        if (isset($ad_big[$k])) {
                            array_push($ads, $ad_big[$k]); //取得相同的键位
                        }

                        array_push($ads, $v);  //大的在前

                    } else {
                        //小的在前
                        array_push($ads, $v);
                        if (isset($ad_big[$k])) {
                            array_push($ads, $ad_big[$k]); //取得相同的键位
                        }
                    }
                }
            }


            return $ads;

        }
    }



}